package com.assess.web.controller;

import com.assess.web.util.RespCode;
import com.assess.web.util.RespParam;
import com.assess.web.util.request.ResponseUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by guoqi.
 */
public class BaseController {


    public <T> RespParam<T> success(T data) {
        RespParam<T> result = new RespParam<T>();
        result.setCode(RespCode.Common.SUCCESS.getCode());
        result.setData(data);
        return result;
    }

    public <T> RespParam<T> fail(RespCode.EnumRespCode errorCode) {
        return fail(errorCode, errorCode.getDesc());
    }

    public <T> RespParam<T> fail(RespCode.EnumRespCode errorCode, String errMsg) {
        RespParam<T> result = new RespParam<T>();
        result.setCode(errorCode.getCode());
        result.setErrMsg(errMsg);
        return result;
    }


    @ExceptionHandler
    public void exceptionHandler(Throwable throwable, HttpServletRequest request, HttpServletResponse response) {
        // 返回错误码
        ResponseUtil.fail(response, RespCode.Common.SYSERROR);
    }

    /**
     * 参数校验错误异常处理
     *
     * @param exception
     * @param response
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public void paramsCheckException(MethodArgumentNotValidException exception, HttpServletResponse response) {
        BindingResult result = exception.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        Map<String, String> errMsg = new HashMap<>();
        for (FieldError error : errors) {
            errMsg.put(error.getField(), error.getDefaultMessage());
        }
        ResponseUtil.fail(response, RespCode.Common.PARAMCHECKERROR, errMsg.toString());
    }

}
